package com.boot.sample.websocket.handler;

import com.boot.sample.websocket.adapter.UserSessionAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Component
public class MyStringWebSocketHandler extends TextWebSocketHandler {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserSessionAdapter userSessionAdapter;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        log.info("和客户端建立连接:"+session.getId());
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        session.close(CloseStatus.SERVER_ERROR);
        log.error("连接异常"+session.getId(), exception);
        userSessionAdapter.userOffline(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
        log.info("和客户端断开连接"+session.getId());
        userSessionAdapter.userOffline(session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 获取到客户端发送过来的消息
        String receiveMessage = message.getPayload();
        log.info(session.getId()+":"+receiveMessage);
        if(receiveMessage.startsWith("online:")){
            String uid=receiveMessage.replace("online:","");
            userSessionAdapter.userOnline(session,uid);
            log.info("online "+uid);
            // 发送消息给客户端
            session.sendMessage(new TextMessage(getSystemMessage("登录成功")));
        }else if(receiveMessage.startsWith("@")){
            String toUid= receiveMessage.substring(1,receiveMessage.indexOf(":"));
            String msg= receiveMessage.substring(receiveMessage.indexOf(":")+1);
            log.info("to msg "+toUid);
            WebSocketSession tosession = userSessionAdapter.getWebSocketSessionByUid(toUid);
            if(null != tosession){
                String username= userSessionAdapter.getUserNameBySessionId(session.getId());
                if(null == username)    username="未知";
                tosession.sendMessage(new TextMessage(getFromMessage(username,msg)));
            }
        }

        // 关闭连接
        // session.close(CloseStatus.NORMAL);
    }

    private static String getSystemMessage(String input) {
        return "系统提示："+input;
    }
    private static String getFromMessage(String from,String input) {
        return "from "+from+"："+input;
    }
    private static String fakeAi(String input) {
        if (input == null || "".equals(input)) {
            return "你说什么？没听清︎";
        }
        return input.replace('你', '我')
                .replace("吗", "")
                .replace('?', '!')
                .replace('？', '！');
    }
}
